<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/13
 * Time: 9:38
 */

include 'db_connect.php';
//mysqli_select_db($con,'tieba');

$postLi = [];
$infoErrorMsg = '';
$successMsg = '';
$pageNow = 1;
$pageCount = 0;
//$userName = [];
//$userName = '';
$isRelease = false;

function init()
{
    //查找数据
    global $con;
    global $postLi;
    global $userName;
    $pageSize = 3;//每页显示数量
    $rowCount = 0;//总数量
    global $pageNow;//当前页数
    //if (!session_id()) session_start();
    //echo $_SESSION['user_id'];
    //$userId = $_SESSION['user_id'];
    //获取用户名
//    $sql = "SELECT name FROM user WHERE id='$userId'";
//    $result = $con->query($sql);
    //global $userName;
//    if ($row = mysqli_fetch_array($result)) {
//        $userName = $row[0];
//    }
    //echo $userName;

    if (!empty($_GET['pageNow'])) {
        $pageNow = $_GET['pageNow'];
    }

    global $pageCount;//总共多少页

    $sql1 = "SELECT COUNT(id) FROM post_li";
    $result1 = $con->query($sql1);

    if ($row1 = mysqli_fetch_array($result1)) {
        $rowCount = $row1[0];
    }
    //echo $rowCount;
    $pageCount = ceil($rowCount/$pageSize);
    //echo $pageCount;
    $pre = ($pageNow-1)*$pageSize;
    $sql2 = "SELECT * FROM post_li limit $pre,$pageSize";
    $postLi = $con->query($sql2);

//    while ($row2 = mysqli_fetch_array($postLi)) {
//        //echo $row2[1];
//        $sql = "SELECT name FROM user WHERE id='$row2[1]'";
//        $result = $con->query($sql);
//        //echo $result;
//        if ($row = mysqli_fetch_array($result)) {
//            echo $row[0];
//
//        }
//        //echo $row2[1];
////        echo $username;
//    }
//    foreach ($postLi as $k => $v) {
//        $id = $v['user_id'];
//        $sql = "SELECT name FROM user WHERE id='$id'";
//        $result2 = $con->query($sql);
//        if ($row2 = mysqli_fetch_array($result2)) {
//            $userName = $row2[0];
//            print_r($userName);
//            //echo $userName[0];
//        }
//    }
//    foreach ($userName as  $v) {
//        echo $v[1];
//    }
    //echo var_dump($postLi);






//    $sql = "SELECT * FROM post_li";
//    $result = $con->query($sql);
//    //echo $postLi;
////    while ($row = mysqli_fetch_array($postLi)) {
////        echo $row['name'].' '.$row['title'].' '.$row['url'].' '.$row['content'].' '.$row['img'].' '.$row['add_time'];
////    }
//
//    $postLi = $result->fetch_all(MYSQLI_ASSOC);
//
//    foreach($postLi as $k => $v){
//        $sql = "SELECT id,name FROM user where id = ". $v['user_id'];
//        $result = $con->query($sql);
//        $postLi[$k]['user'] = $result->fetch_array(MYSQLI_ASSOC);
//    }

}

//function sub_str($str, $start, $len)
//{
//    $temstr = '';
//    $strlen = $len - $start;
//    for ($i = 0; $i < $strlen; $i++) {
//        if(ord(substr($str, $i, 1)) > 0xa0) {
//            $temstr .= substr($str, $i, 3);
//            $i += 2;
//        }else {
//            $temstr .= substr($str, $i, 1);
//        }
//    }
//    return $temstr;
//}

function get_userName($id)
{
    global $con;
    $userName = '';
    $sql = "SELECT name FROM user WHERE id='$id'";
    $result = $con->query($sql);
    if ($row = mysqli_fetch_array($result)) {
        $userName = $row[0];
    }
    return $userName;



}

function publish()
{
    //获取数据
    //echo "sssss";
    global $infoErrorMsg;
    global $con;
    global $isRelease;
    $title = $content = $img = $netImg = '';
    $t = time();
    //$sessionName = '';
//    $lifeTime = 1;
//    session_set_cookie_params($lifeTime);
    if (!session_id()) session_start();
    //if (isset($_SESSION['user_name'])) {
        $userId = $_SESSION['user_id'];
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $title = trim($_POST['title']);
            //$content = substr(trim($_POST['content']),0,6).'...';
            $content = trim($_POST['content']);
            $netImg = trim($_POST['netImg']);
        }
        //图片上传
        if (!empty($_FILES["file"]["tmp_name"])) {
            if ($_FILES["file"]["error"] > 0) {
                echo "错误".$_FILES["file"]["error"]."<br />";
            }
            if (file_exists("upload/".$_FILES["file"]["name"])) {
                //echo $_FILES["file"]["name"].'文件已存在';
                $img = "upload/".$_FILES["file"]["name"];
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
                //echo "文件已经被存储到:"."upload/".$_FILES["file"]["name"];
                $img ="upload/".$_FILES["file"]["name"];
            }



//            if ($_FILES["file"]["error"] > 0)
//            {
//                echo "错误：" . $_FILES["file"]["error"] . "<br>";
//            }
//            else
//            {
////        echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
////        echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
////        echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
//                echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"];
//            }
//            if (file_exists("upload/".$_FILES["file"]["name"])) {
//                echo $_FILES["file"]["name"]."文件已经存在.";
//                //$avatars = "upload/".$_FILES["file"]["name"];
//            } else {
//                move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
//                echo "文件已经被存储到:"."upload/".$_FILES["file"]["name"];
//                //$avatars = "upload/".$_FILES["file"]["name"];
//            }



        } elseif(!empty($netImg)) {
            $img = $netImg;
        }else {
            $img = '';
        }

//        echo $title.' '.$url.' '.$content.' '.$img." ".$t.' ';

        //录入数据库
        if ($title == '' || $content == '') {
            $infoErrorMsg = '标题或内容不能为空!';
            $isRelease = true;
            init();
            //echo '标题或内容不能为空!';
            return;
        }
        $inserts = "INSERT INTO post_li(user_id, title, content, img, add_time) VALUE ('$userId', '$title', '$content', '$img', '$t')";
        $con->query($inserts);
        init();
    return;
}

function gotoRegist()
{
    header('location:user.php');
}

function release()
{
    global $isRelease;
    global $infoErrorMsg;
//    $lifeTime = 1;
//    session_set_cookie_params($lifeTime);
    if (!session_id()) session_start();
    if (!isset($_SESSION['user_name'])) {
        $infoErrorMsg = '登录后才能发帖！';
    } else {
        $isRelease = true;
    }
}

function main()
{
    $psot = $_POST;
    $act = '';

    isset($psot['act']) && $act = $psot['act'];

    if ($act == 'publish') {
        publish();
        return;
    }

    if ($act == 'gotoRegist') {
        gotoRegist();
        return;
    }

    if ($act == 'release') {
        release();
       // $isRelease = true;
    }
    init();
}
main();
?>

<!DOCTYPE html>
<!--STATUS OK-->
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="search" type="application/opensearchdescription+xml" href="/tb/cms/content-search.xml" title="百度贴吧" />
    <meta name="keywords" content="复仇者联盟,欧美电影,电影,1资源,3资源">
    <title>主页</title>
    <style>
        li a{
            display: block;
        }
        ul li{
            border:1px solid rgba(0,0,0,.3);
        }
        .error{
            color: #f00;
        }
    </style>
</head>
<body>
<?php include 'public/head.php'; ?>
<?php //session_start();if(isset($_SESSION['user_name'])) { ?>
<!--    <ul>-->
<!--        --><?php //foreach($arr as $k => $v){?>
<!--            <li>-->
<!--                <a href="--><?php //echo $v['url'];?><!--"><h3>--><?php //echo $v['title'];?><!--</h3></a>-->
<!--                <h5>--><?php //echo $v['title2'];?><!--</h5>-->
<!--                <img src="--><?php //echo $v['img']?><!--" alt="">-->
<!--            </li>-->
<!--        --><?php //}?>
<!--    </ul>-->
<?php //} else {?>
<!--    --><?php //header('location:user.php')?>
<?php //} ?>
<!--<ul>-->
<!--    --><?php //foreach ($postLi as $k => $v) {  ?>
<!--    <li>-->
<!--        <a href="/detail.php?id=--><?php //echo $v['id']; ?><!--"><h3>--><?php //echo $v['title'];?><!--</h3></a>-->
<!--        <h5>--><?php //echo  $v['content'];?><!--</h5>-->
<!--        --><?php //if ($v['img'] != '') { ?>
<!--        <img src="--><?php //echo $v['img'];?><!--" alt="" width="150"><br />-->
<!--        --><?php //} ?>
<!--        <span>作者:--><?php //echo $v['user']['name']; ?><!--</span>&nbsp;<span>-->
<!--            发帖时间:--><?php //echo date("Y-m-d h:i",$v['add_time']);?><!--</span>-->
<!--    </li>-->
<!--    --><?php //} ?>
<!--</ul>-->
<?php if(!$isRelease) {?>
<ul>
    <?php foreach ($postLi as $k => $v) {?>
        <li>
            <a href="/detail.php?id=<?php echo $v['id'];?>"><h3><?php echo $v['title'];?></h3></a>
            <h5><?php if(strlen($v['content']) > 10) {?>
                <?php echo mb_substr($v['content'],0,10).'...';?>
                <?php } else {?>
                <?php echo $v['content'];?>
                <?php }?>
            </h5>
            <?php if (!$v['img'] == '') {?>
            <img src="<?php echo $v['img'];?>" alt="" width="100"><br />
            <?php }?>
            <span>作者:<?php
                $id = $v['user_id'];
//                    $sql = "SELECT name FROM user WHERE id='$id'";
//                    $result = $con->query($sql);
                    //echo $result;
//                    if ($row = mysqli_fetch_array($userName)) {
//                        echo $row[0];
//                    }
                echo get_userName($id);
                ?></span>
            <span>发帖时间:<?php echo date("Y-m-d h:i",$v['add_time']);?></span>
        </li>
    <?php }?>
</ul>
<?php
//if($pageNow>1){
//    $prePage = $pageNow-1;
//    echo "<a href='index.php?pageNow=$prePage'>pre</a>&nbsp;";
//}
//if($pageNow<$pageCount){
//    $nextPage = $pageNow+1;
//    echo "<a href='index.php?pageNow=$nextPage'>next</a>&nbsp;";
//    //echo "当前页{$pageNow}/共{$pageCount}页";
//}
//echo "当前页{$pageNow}/共{$pageCount}页";
//?>
<div>
    <?php for($i=1;$i<=$pageCount;$i++) {?>
        <?php if($pageNow == $i) {?>
            <span><?php echo $i;?></span>
        <?php } else {?>
            <a href="index.php?pageNow=<?php echo $i;?>"><?php echo $i;?></a>
        <?php }?>
    <?php }?>
    <a href="index.php?pageNow=1">首页</a>
    <a href="index.php?pageNow=<?php echo $pageNow==1?1:($pageNow-1)?>">上一页</a>
    <a href="index.php?pageNow=<?php echo $pageNow==$pageCount?$pageCount:($pageNow+1)?>">下一页</a>
    <a href="index.php?pageNow=<?php echo $pageCount?>">尾页</a><?php echo "当前页{$pageNow}/共{$pageCount}页"?>
</div>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>" METHOD="post">
    <fieldset>
        <legend>我要发帖</legend>
        <input type="hidden" name="act" value="release">
        <input type="submit" value="发帖">
    </fieldset>
</form>
<?php if(isset($infoErrorMsg)) { ?>
    <span class="error"><?php echo $infoErrorMsg; ?></span>
<?php } ?>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    <fieldset>
        <legend>前往登录/注册</legend>
        <input type="hidden" name="act" value="gotoRegist">
        <input type="submit" value="登录/注册">
    </fieldset>
</form>
<?php } else {?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
    <fieldset>
        <legend>发表新帖</legend>
<!--        --><?php //$sessionName = $_SESSION['user_name']; ?>
        标题:<input type="text" name="title"><br /><br />
        内容:<textarea name="content" id="content" cols="70" rows="15"></textarea><br />
        <input type="hidden" name="act" value="publish"><br />
<!--        <input type="hidden" name="url" value="detail.php?id=1"><br />-->
<!--        <input type="hidden" name="sessionName" value="--><?php //echo $sessionName; ?><!--">-->
        <label for="netImg"></label>
        网络图片地址:<input type="text" name="netImg"><br /><br />
        <label for="file">本地图片:</label>
        <input type="file" name="file" id="file"><br />
        <input type="submit" value="发表">
    </fieldset>
</form>
<?php if(isset($infoErrorMsg)) { ?>
    <span class="error"><?php echo $infoErrorMsg; ?></span>
<?php } ?>
<?php }?>
</body>
</html>


